<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

//餐饮系统
namespace app\custom;
use think\facade\Db;
use think\facade\Log;

class Restaurant {
	public static function getmenu($isadmin) {
		// //点餐
		// $restaurant_child = [];
		// $restaurant_child[] = ['name'=>'首页','path'=>'Restaurant/index','authdata'=>'Restaurant/*'];
		// //菜品
		// $restaurant_product[] = ['name'=>'菜品列表','path'=>'RestaurantProduct/index','authdata'=>'RestaurantProduct/*'];
		// $restaurant_product[] = ['name'=>'菜品分类','path'=>'RestaurantProductCategory/index','authdata'=>'RestaurantProductCategory/*'];
		//       $restaurant_product[] = ['name'=>'菜品采集','path'=>'RestaurantTaobao/index','authdata'=>'RestaurantTaobao/*'];
		// $restaurant_child[] = ['name'=>'菜品','child'=>$restaurant_product];

		// //外卖
		// $restaurant_waimai[] = ['name'=>'外卖订单','path'=>'RestaurantTakeawayOrder/index','authdata'=>'RestaurantTakeawayOrder/*'];
		// $restaurant_waimai[] = ['name'=>'评价管理','path'=>'RestaurantTakeawayComment/index','authdata'=>'RestaurantTakeawayComment/*'];
		// $restaurant_waimai[] = ['name'=>'配送方式','path'=>'RestaurantTakeawayFreight/index','authdata'=>'RestaurantTakeawayFreight/*'];
		// $restaurant_waimai[] = ['name'=>'外卖设置','path'=>'RestaurantTakeawaySet/index','authdata'=>'RestaurantTakeawaySet/*'];
		// $restaurant_child[] = ['name'=>'外卖','child'=>$restaurant_waimai];

		// //店内点餐
		// $restaurant_shop[] = ['name'=>'点餐订单','path'=>'RestaurantShopOrder/index','authdata'=>'RestaurantShopOrder/*'];
		// $restaurant_shop[] = ['name'=>'评价管理','path'=>'RestaurantShopComment/index','authdata'=>'RestaurantShopComment/*'];
		// $restaurant_shop[] = ['name'=>'点餐设置','path'=>'RestaurantShopSet/index','authdata'=>'RestaurantShopSet/*'];
		// $restaurant_child[] = ['name'=>'点餐','child'=>$restaurant_shop];

		// //预定
		// $restaurant_booking[] = ['name'=>'预定订单','path'=>'RestaurantBookingOrder/index','authdata'=>'RestaurantBookingOrder/*'];
		// $restaurant_booking[] = ['name'=>'预定设置','path'=>'RestaurantBookingSet/index','authdata'=>'RestaurantBookingSet/*'];
		// $restaurant_child[] = ['name'=>'预定','child'=>$restaurant_booking];

		// //排队
		// $restaurant_queue[] = ['name'=>'排队队列','path'=>'RestaurantQueue/index','authdata'=>'RestaurantQueue/*'];
		// $restaurant_queue[] = ['name'=>'队列设置','path'=>'RestaurantQueueCategory/index','authdata'=>'RestaurantQueueCategory/*'];
		// $restaurant_queue[] = ['name'=>'排队设置','path'=>'RestaurantQueueSet/index','authdata'=>'RestaurantQueueSet/*'];
		// $restaurant_child[] = ['name'=>'排队','child'=>$restaurant_queue];

		// //寄存
		// $restaurant_deposit[] = ['name'=>'寄存管理','path'=>'RestaurantDeposit/index','authdata'=>'RestaurantDeposit/*'];
		// $restaurant_deposit[] = ['name'=>'添加寄存','path'=>'RestaurantDeposit/edit','authdata'=>'RestaurantDeposit/*'];
		// $restaurant_deposit[] = ['name'=>'寄存设置','path'=>'RestaurantDepositSet/index','authdata'=>'RestaurantDepositSet/*'];
		// $restaurant_child[] = ['name'=>'寄存','child'=>$restaurant_deposit];

		// //餐桌
		// $restaurant_tables[] = ['name'=>'餐桌列表','path'=>'RestaurantTable/index','authdata'=>'RestaurantTable/*'];
		// $restaurant_tables[] = ['name'=>'餐桌分类','path'=>'RestaurantTableCategory/index','authdata'=>'RestaurantTableCategory/*'];
		// $restaurant_child[] = ['name'=>'餐桌','child'=>$restaurant_tables];

		// $yingxiao_child = [];
		// $yingxiao_child[] = ['name'=>t('优惠券'),'path'=>'RestaurantCoupon/index','authdata'=>'RestaurantCoupon/*,RestaurantProductCategory/index,RestaurantProductCategory/choosecategory'];
		// $yingxiao_child[] = ['name'=>'促销','path'=>'RestaurantCuxiao/index','authdata'=>'RestaurantCuxiao/*'];
		// $restaurant_child[] = ['name'=>'营销','child'=>$yingxiao_child];

		//       $restaurant_child[] = ['name'=>'餐厅区域打印','path'=>'RestaurantPrint/index','authdata'=>'RestaurantPrint/*'];

		// if($isadmin){
		// 	$restaurant_child[] = ['name'=>'设置','path'=>'Restaurant/sysset','authdata'=>'Restaurant/*'];
		// }
		$yuyue_child = [];
		$yuyue_child[] = ['name' => '服务类型', 'path' => 'Yuyue/index', 'authdata' => 'Yuyue/*'];
		$yuyue_child[] = ['name' => '服务商品', 'path' => 'YuyueList/index', 'authdata' => 'YuyueList/*'];
		$yuyue_child[] = ['name' => '服务订单', 'path' => 'YuyueOrder/index', 'authdata' => 'YuyueOrder/*'];

		return ['name' => '预约', 'fullname' => '预约服务', 'icon' => 'my-icon my-icon-shop', 'child' => $yuyue_child];
	}
	//配送方式默认
	public static function init_freight($aid, $bid) {
		$freight = Db::name('restaurant_takeaway_freight')->where('bid', $bid)->find();
		if (!$freight) {
			Db::name('restaurant_takeaway_freight')->insert([
				'aid' => $aid,
				'bid' => $bid,
				'name' => '同城配送',
				'pstype' => 2,
				'pricedata' => '[{"region":"全国(默认运费)","fristweight":"1000","fristprice":"0","secondweight":"1000","secondprice":"0"}]',
				'pstimedata' => '[{"day":"1","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"1","hour":"18","minute":"0","hour2":"18","minute2":"30"},{"day":"2","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"2","hour":"18","minute":"0","hour2":"18","minute2":"30"}]',
				'psprehour' => 4,
				'peisong_juli1' => 5,
				'peisong_fee1' => 3,
				'peisong_juli2' => 1,
				'peisong_fee2' => 1,
				'peisong_lng' => $business['longitude'],
				'peisong_lat' => $business['latitude'],
				'peisong_range' => 2000,
				'status' => 1,
			]);
			Db::name('restaurant_takeaway_freight')->insert([
				'aid' => $aid,
				'bid' => $bid,
				'name' => '到店自提',
				'pstype' => 1,
				'pricedata' => '[{"region":"全国(默认运费)","fristweight":"1000","fristprice":"0","secondweight":"1000","secondprice":"0"}]',
				'pstimedata' => '[{"day":"1","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"1","hour":"18","minute":"0","hour2":"18","minute2":"30"},{"day":"2","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"2","hour":"18","minute":"0","hour2":"18","minute2":"30"}]',
				'status' => 1,
			]);
		}
		$info = Db::name('restaurant_takeaway_sysset')->where('aid', $aid)->where('bid', $bid)->find();
		if (!$info) {
			Db::name('restaurant_takeaway_sysset')->insert(['aid' => $aid, 'bid' => $bid]);
		}
	}
	//外卖订单完成
	public static function takeaway_orderconfirm($orderid) {
		$order = Db::name('restaurant_takeaway_order')->where('id', $orderid)->find();
		if ($order['status'] == 3) {
			return ['status' => 0, 'msg' => '订单已完成'];
		}

		// 启动事务
		Db::startTrans();
		try {
			Db::name('restaurant_takeaway_order')->where('id', $orderid)->update(['status' => 3, 'collect_time' => time()]);
			Db::name('restaurant_takeaway_order_goods')->where('orderid', $orderid)->update(['status' => 3]);
			$aid = $order['aid'];
			if ($order['bid'] != 0) {
				//店铺加销量
				$totalnum = Db::name('restaurant_takeaway_order_goods')->where('aid', $aid)->where('orderid', $order['id'])->sum('num');
				Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->inc('sales', $totalnum)->update();
			}
			if (!$order['paytypeid']) {
				return ['status' => 1, 'msg' => ''];
			}

			$oglist = Db::name('restaurant_takeaway_order_goods')->where('aid', $aid)->where('orderid', $order['id'])->select()->toArray();
			if ($order['bid'] != 0) {
//入驻商家的货款
				$totalcommission = 0;
				foreach ($oglist as $og) {
					if ($og['iscommission']) {
						continue;
					}

					if ($og['parent1'] && $og['parent1commission'] > 0) {
						$totalcommission += $og['parent1commission'];
					}
					if ($og['parent2'] && $og['parent2commission'] > 0) {
						$totalcommission += $og['parent2commission'];
					}
					if ($og['parent3'] && $og['parent3commission'] > 0) {
						$totalcommission += $og['parent3commission'];
					}
				}
				$binfo = Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid', $aid)->find();
				if ($bset['commission_kouchu'] == 0) {
					//不扣除佣金
					$totalcommission = 0;
				}
				$totalmoney = $order['product_price'] + $order['pack_fee'] + $order['freight_price'] - $order['coupon_money'] - $order['manjia_money'] - $totalcommission;
				if ($totalmoney > 0) {
					$totalmoney = $totalmoney * (100 - $binfo['feepercent']) * 0.01;
				}
				if ($totalmoney < 0) {
					$bmoney = Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->value('money');
					if ($bmoney + $totalmoney < 0) {
						return ['status' => 0, 'msg' => '操作失败,商家余额不足'];
					}
				}
				\app\common\Business::addmoney($aid, $order['bid'], $totalmoney, '货款，外卖订单号：' . $order['ordernum']);
				Db::name('restaurant_takeaway_order_goods')->where('aid', $aid)->where('orderid', $orderid)->update(['iscommission' => 1]);
			}
			//赠积分
			if ($order['givescore'] > 0) {
				\app\common\Member::addscore(aid, $order['mid'], $order['givescore'], '购买菜品赠送' . t('积分'));
			}

			//佣金
			$commission_record_list = Db::name('member_commission_record')->where('aid', $aid)->where('type', 'restaurant_takeaway')->where('orderid', $order['id'])->where('status', 0)->select();
			foreach ($commission_record_list as $commission_record) {
				$og = Db::name('restaurant_takeaway_order_goods')->where('id', $commission_record['ogid'])->find();
				if ($commission_record['commission'] > 0) {
					\app\common\Member::addcommission($aid, $commission_record['mid'], $commission_record['frommid'], $commission_record['commission'], $commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销菜品获得' . t('佣金') . '：￥' . $commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $og['name']; //商品信息
					$tmplcontent['keyword2'] = $og['sell_price']; //商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'] . '元'; //商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s', $commission_record['createtime']); //分销时间
					$rs = \app\common\Wechat::sendtmpl($aid, $commission_record['mid'], 'tmpl_fenxiaosuccess', $tmplcontent, m_url('pages/my/usercenter'));
					//短信通知
					$tel = Db::name('member')->where('id', $commission_record['mid'])->value('tel');
					$rs = \app\common\Sms::send($aid, $tel, 'tmpl_fenxiaosuccess', ['money' => $commission_record['commission']]);
				}
				if ($commission_record['score'] > 0) {
					\app\common\Member::addscore($aid, $commission_record['mid'], $commission_record['score'], $commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销菜品获得：' . $commission_record['mid'] . t('积分');
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $og['name']; //商品信息
					$tmplcontent['keyword2'] = $og['sell_price']; //商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'] . t('积分'); //商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s', $commission_record['createtime']); //分销时间
					$rs = \app\common\Wechat::sendtmpl($aid, $commission_record['mid'], 'tmpl_fenxiaosuccess', $tmplcontent, m_url('pages/my/usercenter'));
					//短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
					//$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
				Db::name('member_commission_record')->where('id', $commission_record['id'])->update(['status' => 1, 'endtime' => time()]);
			}
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
		}

		return ['status' => 1, 'msg' => ''];
	}
	//点餐订单完成
	public static function shop_orderconfirm($orderid) {
		$order = Db::name('restaurant_shop_order')->where('id', $orderid)->find();
		if (empty($order)) {
			return ['status' => 0, 'msg' => '订单不存在'];
		}

		if ($order['status'] == 3) {
			return ['status' => 0, 'msg' => '订单已完成'];
		}

		$aid = $order['aid'];
		if ($order['bid'] != 0) {
			//店铺加销量
			$totalnum = Db::name('restaurant_takeaway_order_goods')->where('aid', $aid)->where('orderid', $order['id'])->sum('num');
			Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->inc('sales', $totalnum)->update();
		}
//		if(!$order['paytypeid']) return ['status'=>1,'msg'=>''];
		$oglist = Db::name('restaurant_shop_order_goods')->where('aid', $aid)->where('orderid', $order['id'])->select()->toArray();
		if ($order['bid'] != 0) {
//入驻商家的货款
			$totalcommission = 0;
			foreach ($oglist as $og) {
				if ($og['iscommission']) {
					continue;
				}

				if ($og['parent1'] && $og['parent1commission'] > 0) {
					$totalcommission += $og['parent1commission'];
				}
				if ($og['parent2'] && $og['parent2commission'] > 0) {
					$totalcommission += $og['parent2commission'];
				}
				if ($og['parent3'] && $og['parent3commission'] > 0) {
					$totalcommission += $og['parent3commission'];
				}
			}
			$binfo = Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->find();
			$bset = Db::name('business_sysset')->where('aid', $aid)->find();
			if ($bset['commission_kouchu'] == 0) {
				//不扣除佣金
				$totalcommission = 0;
			}
			$totalmoney = $order['totalprice'] + $order['scoredk_money'] - $totalcommission;
			if ($totalmoney > 0) {
				$totalmoney = $totalmoney * (100 - $binfo['feepercent']) * 0.01;
			}
			if ($order['paytypeid'] == 4 || empty($order['paytype'])) {
				$totalmoney = $totalmoney - $order['totalprice'];
			}
			if ($totalmoney < 0) {
				$bmoney = Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->value('money');
				if ($bmoney + $totalmoney < 0) {
					return ['status' => 0, 'msg' => '操作失败,商家余额不足'];
				}
			}
			\app\common\Business::addmoney($aid, $order['bid'], $totalmoney, '货款，订单号：' . $order['ordernum']);
			Db::name('restaurant_shop_order_goods')->where('aid', $aid)->where('orderid', $orderid)->update(['iscommission' => 1]);
		}
		//赠积分
		if ($order['givescore'] > 0) {
			\app\common\Member::addscore(aid, $order['mid'], $order['givescore'], '购买菜品赠送' . t('积分'));
		}

		//佣金
		$commission_record_list = Db::name('member_commission_record')->where('aid', $aid)->where('type', 'restaurant_shop')->where('orderid', $order['id'])->where('status', 0)->select();
		foreach ($commission_record_list as $commission_record) {
			$og = Db::name('restaurant_shop_order_goods')->where('id', $commission_record['ogid'])->find();
			if ($commission_record['commission'] > 0) {
				\app\common\Member::addcommission($aid, $commission_record['mid'], $commission_record['frommid'], $commission_record['commission'], $commission_record['remark']);
				$tmplcontent = [];
				$tmplcontent['first'] = '恭喜您，成功分销菜品获得' . t('佣金') . '：￥' . $commission_record['commission'];
				$tmplcontent['remark'] = '点击进入查看~';
				$tmplcontent['keyword1'] = $og['name']; //商品信息
				$tmplcontent['keyword2'] = $og['sell_price']; //商品单价
				$tmplcontent['keyword3'] = $commission_record['commission'] . '元'; //商品佣金
				$tmplcontent['keyword4'] = date('Y-m-d H:i:s', $commission_record['createtime']); //分销时间
				$rs = \app\common\Wechat::sendtmpl($aid, $commission_record['mid'], 'tmpl_fenxiaosuccess', $tmplcontent, m_url('pages/my/usercenter'));
				//短信通知
				$tel = Db::name('member')->where('id', $commission_record['mid'])->value('tel');
				$rs = \app\common\Sms::send($aid, $tel, 'tmpl_fenxiaosuccess', ['money' => $commission_record['commission']]);
			}
			if ($commission_record['score'] > 0) {
				\app\common\Member::addscore($aid, $commission_record['mid'], $commission_record['score'], $commission_record['remark']);
				$tmplcontent = [];
				$tmplcontent['first'] = '恭喜您，成功分销菜品获得：' . $commission_record['mid'] . t('积分');
				$tmplcontent['remark'] = '点击进入查看~';
				$tmplcontent['keyword1'] = $og['name']; //商品信息
				$tmplcontent['keyword2'] = $og['sell_price']; //商品单价
				$tmplcontent['keyword3'] = $commission_record['commission'] . t('积分'); //商品佣金
				$tmplcontent['keyword4'] = date('Y-m-d H:i:s', $commission_record['createtime']); //分销时间
				$rs = \app\common\Wechat::sendtmpl($aid, $commission_record['mid'], 'tmpl_fenxiaosuccess', $tmplcontent, m_url('pages/my/usercenter'));
				//短信通知
				//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
				//$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
			}
			Db::name('member_commission_record')->where('id', $commission_record['id'])->update(['status' => 1, 'endtime' => time()]);
		}
		Db::name('restaurant_shop_order')->where('id', $orderid)->update(['status' => 3, 'collect_time' => time()]);
		Db::name('restaurant_shop_order_goods')->where('orderid', $orderid)->update(['status' => 3]);
		return ['status' => 1, 'msg' => ''];
	}

	//预定订单完成
	public static function booking_orderconfirm($orderid) {
		$order = Db::name('restaurant_booking_order')->where('id', $orderid)->find();
		if (empty($order)) {
			return ['status' => 0, 'msg' => '订单不存在'];
		}

		if ($order['status'] == 3) {
			return ['status' => 0, 'msg' => '订单已完成'];
		}

		$aid = $order['aid'];
		if ($order['bid'] != 0 && $order['totalprice'] > 0) {
//入驻商家的货款
			$totalcommission = 0;
			$binfo = Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->find();
			$bset = Db::name('business_sysset')->where('aid', $aid)->find();
			$totalmoney = $order['totalprice'] + $order['scoredk_money'] - $totalcommission;
			if ($totalmoney > 0) {
				$totalmoney = $totalmoney * (100 - $binfo['feepercent']) * 0.01;
			}
			if ($order['paytypeid'] == 4 || empty($order['paytype'])) {
				$totalmoney = $totalmoney - $order['totalprice'];
			}
			if ($totalmoney < 0) {
				$bmoney = Db::name('business')->where('aid', $aid)->where('id', $order['bid'])->value('money');
				if ($bmoney + $totalmoney < 0) {
					return ['status' => 0, 'msg' => '操作失败,商家余额不足'];
				}
			}
			\app\common\Business::addmoney($aid, $order['bid'], $totalmoney, '货款，订单号：' . $order['ordernum']);
		}

		Db::name('restaurant_booking_order')->where('aid', $aid)->where('bid', $order['bid'])->where('id', $orderid)->update(['status' => 3, 'collect_time' => time()]);
		Db::name('restaurant_booking_order_goods')->where('aid', $aid)->where('bid', $order['bid'])->where('orderid', $orderid)->update(['status' => 3, 'endtime' => time()]);
		return ['status' => 1, 'msg' => ''];
	}
	//排队叫号
	public static function call_no($aid, $text) {
		$set = Db::name('restaurant_admin_set')->where('aid', $aid)->find();

		$text = str_replace('0', '零', $text);

		$reqArr = array();
		$reqArr['Action'] = 'TextToStreamAudio';
		$reqArr['AppId'] = intval($set['queue_appid']);
		$reqArr['SecretId'] = $set['queue_secretid'];
		$reqArr['Timestamp'] = time();
		$reqArr['Expired'] = 3600 + time(); //表示为离线识别
		$reqArr['Text'] = $text;
		$reqArr['SessionId'] = self::guid();
		$reqArr['Codec'] = 'mp3';
		$reqArr['VoiceType'] = $set['queue_voicetype'] ? intval($set['queue_voicetype']) : 0;

		$serverUrl = "https://tts.cloud.tencent.com/stream";
		$autho = self::createSign($reqArr, "POST", "tts.cloud.tencent.com", "/stream", $set['queue_secretkey']);
		$header = array('Authorization: ' . $autho, 'Content-Type: ' . 'application/json');

		$rs = curl_post($serverUrl, jsonEncode($reqArr), 0, $header);
		return $rs;
	}
	public static function createSign($reqArr, $method, $domain, $path, $secretKey) {
		$signStr = "";
		$signStr .= $method;
		$signStr .= $domain;
		$signStr .= $path;
		$signStr .= "?";
		ksort($reqArr, SORT_STRING);

		foreach ($reqArr as $key => $val) {
			$signStr .= $key . "=" . $val . "&";
		}
		$signStr = substr($signStr, 0, -1);
		$signStr = base64_encode(hash_hmac('SHA1', $signStr, $secretKey, true));

		return $signStr;
	}
	public static function guid() {
		if (function_exists('com_create_guid')) {
			return com_create_guid();
		} else {
			mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45); // "-"
			$uuid =
			substr($charid, 0, 8) . $hyphen
			. substr($charid, 8, 4) . $hyphen
			. substr($charid, 12, 4) . $hyphen
			. substr($charid, 16, 4) . $hyphen
			. substr($charid, 20, 12);
			return $uuid;
		}
	}
	//计划任务 每分钟执行一次
	public static function auto_perminute() {
		if (date('H') == '00' && cache('restaurant_cleardaysalesday') != date('Ymd')) {
			//零点清商品每日库存
			cache('restaurant_cleardaysalesday', date('Ymd'));
			Db::name('restaurant_product')->where('sales_daily', '<>', 0)->update(['sales_daily', 0]);
			Db::name('restaurant_product_guige')->where('sales_daily', '<>', 0)->update(['sales_daily', 0]);
		}
		//自动关闭订单 释放库存
		$orderlist = Db::name('restaurant_takeaway_order')->where('status', 0)->select()->toArray();
		$autocloseArr = [];
		foreach ($orderlist as $order) {
			if (!$autocloseArr[$order['aid']]) {
				$autocloseArr[$order['aid']] = Db::name('restaurant_admin_set')->where('aid', $order['aid'])->value('takeaway_autoclose');
			}
			if ($order['createtime'] + $autocloseArr[$order['aid']] * 60 > time()) {
				continue;
			}

			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('restaurant_takeaway_order')->where('id', $orderid)->find();
			if (!$order || $order['status'] != 0) {
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			} else {
				//加库存
				$oglist = Db::name('shop_order_goods')->where('aid', $aid)->where('orderid', $orderid)->select()->toArray();
				foreach ($oglist as $og) {
					Db::name('restaurant_product_guige')->where('aid', $aid)->where('id', $og['ggid'])->update(['stock' => Db::raw("stock+" . $og['num']), 'sales' => Db::raw("sales-" . $og['num']), 'sales_daily' => Db::raw("sales_daily-" . $og['num'])]);
					Db::name('restaurant_product')->where('aid', $aid)->where('id', $og['proid'])->update(['stock' => Db::raw("stock+" . $og['num']), 'sales' => Db::raw("sales-" . $og['num']), 'sales_daily' => Db::raw("sales_daily-" . $og['num'])]);
				}
				//优惠券抵扣的返还
				if ($order['coupon_rid'] > 0) {
					Db::name('coupon_record')->where('aid', $aid)->where('mid', $mid)->where('id', $order['coupon_rid'])->update(['status' => 0, 'usetime' => '']);
				}
				$rs = Db::name('restaurant_takeaway_order')->where('id', $orderid)->where('aid', $aid)->where('mid', $mid)->update(['status' => 4]);
				Db::name('restaurant_takeaway_order_goods')->where('orderid', $orderid)->where('aid', $aid)->where('mid', $mid)->update(['status' => 4]);
			}
		}
	}
	//计划任务 每小时执行一次
	public static function auto_perhour() {
		$time = time();
		//外卖自动收货
		$setlist = Db::name('restaurant_takeaway_sysset')->select()->toArray();
		foreach ($setlist as $sysset) {
			$aid = $sysset['aid'];
			if ($aid) {
				$list = Db::name('restaurant_takeaway_order')->where("aid={$aid} and status=2 and " . time() . ">`send_time` + 86400*" . $sysset['autoshdays'])->select()->toArray();
				foreach ($list as $order) {
					$rs = self::takeaway_orderconfirm($order['id']);
//                    if($rs['status'] == 0) continue;
					//                    Db::name('restaurant_takeaway_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}
		//每天4点
		if (date('G') == 4) {
			self::auto_perday();
		}
	}

	public static function auto_perday() {
		//清0每日销量
		Db::name('restaurant_product')->update(['sales_daily' => 0]);
		Db::name('restaurant_product_guige')->update(['sales_daily' => 0]);
	}

	//打印小票 aid 模块 订单号
	/**
	 * @param $title
	 * @param $machineType 0易联云，1飞蛾
	 * @param array $area  print_template_type 0普通打印，1一菜一单;id
	 * @param null $orderType
	 * @param array $orderInfo
	 * @param array $orderGoods
	 * @return string
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function restaurantPrintContent($title, $machineType, $area = [], $orderType = null, $orderInfo = [], $orderGoods = []) {
		if ($orderType != 'test') {
			$order = $orderInfo;
			if (!$order['bid']) {
				$order['bid'] = 0;
			}

			$shop_set = Db::name('restaurant_shop_sysset')->where('aid', $order['aid'])->where('bid', $order['bid'])->find();
		}

		$templateType = $area['print_template_type'];

		$printnum = 0;
		$paytime = $order['paytime'] ? date('Y-m-d H:i:s', $order['paytime']) : '未付款';
		if ($machineType == 0) {
			//易联云
			if ($templateType == 0) {
				//普通打印
				$content = '';
				$content .= "<FS><center>** " . $title . " **</center></FS>\r\r";
				if ($order['tableName']) {
					$content .= "<FS>桌号：" . $order['tableName'] . "</FS>\r";
				}

				$content .= "订单编号：" . $order['ordernum'] . "\r";
				if ($orderType == 'restaurant_takeaway') {
					$content .= "配送方式：" . $order['freight_text'] . "\r";
					if ($order['freight_time']) {
						$content .= "配送时间：<FS>" . $order['freight_time'] . "</FS>\r";
					}
					$content .= "收货人:<FS>" . $order['linkman'] . "</FS>\r";
					$content .= "联系电话:<FS>" . $order['tel'] . "</FS>\r";
					$content .= "收货地址:<FS>" . $order['area'] . " " . $order['address'] . "</FS>\r";
				}

				$content .= "下单时间：" . date('Y-m-d H:i:s', $order['createtime']) . "\r";
				$content .= "付款时间：" . $paytime . "\r";
				$content .= "付款方式：" . $order['paytype'] . "\r\r";
				$content .= "<table>";
				$content .= "<tr><td>商品名称</td><td>数量</td><td>总价</td></tr>";
				foreach ($orderGoods as $item) {
					$content .= "<tr><td><FB>" . $item['name'] . '(' . $item['ggname'] . ')' . "</FB></td><td>" . $item['num'] . "</td><td>" . $item['totalprice'] . "</td></tr>";
				}
				$content .= "</table>";
				$content .= "\r";
				if ($order['message']) {
					$content .= "备注：<FS>" . $order['message'] . "</FS>\r\r";
				} else {
					$content .= "备注：无\r";
				}
				if ($order['tea_fee']) {
					$content .= "<right>" . $shop_set['tea_fee_text'] . "：￥" . $order['tea_fee'] . "</right>\r";
				}
				if ($order['scoredk_money'] > 0) {
					$content .= "<right>积分抵扣：-￥" . $order['scoredk_money'] . "</right>\r";
				}
				if ($order['leveldk_money'] > 0) {
					$content .= "<right>会员等级优惠：-￥" . $order['leveldk_money'] . "</right>\r";
				}
				if ($order['coupon_money'] > 0) {
					$content .= "<right>优惠券：-￥" . $order['coupon_money'] . "</right>\r";
				}
				if ($order['discount_money'] > 0) {
					$content .= "<right>优惠：-￥" . $order['discount_money'] . "</right>\r";
				}
				if ($order['pack_fee'] > 0) {
					$content .= "<right>打包费：+￥" . $order['pack_fee'] . "</right>\r";
				}
				$content .= "<right>实付金额：￥" . $order['totalprice'] . "</right>\r";
				$content .= "\r\r";
			} elseif ($templateType == 1) {
				//一菜一单
				if ($orderType == 'test') {
					$time = date('Y-m-d H:i:s', time());
					$arr = array('酸菜鱼', '可乐鸡翅');
					$content = '';
					$num = count($arr);
					foreach ($arr as $key => $value) {
						$content .= "<FS2><center>**桌号：01**</center></FS2>\r\r";
						$content .= "<FH2><center>" . $value . "  * 1</center></FH2>\r";
						$content .= "@@2备注：不要辣，少盐\r";
						$content .= "时间：" . $time . "\r";
//                        $end = array_keys($arr);
						//                        if(end($end)==$key){
						//                            break;
						//                        }else{
						$content .= "\r\r\r\r<MK2></MK2>\r"; //控制切纸
						//                        }
					}
				} else {
					$content = '';
					foreach ($orderGoods as $key => $item) {
						if ($item['area_id'] != $area['id']) {
							continue;
						}

						$content .= "<FS2><center>**桌号：" . $order['tableName'] . "**</center></FS2>\r\r";
						$content .= "<FH2><center>" . $item['name'] . "(" . $item['ggname'] . ")" . "  * " . $item['num'] . "</center></FH2>\r";
						if ($order['message']) {
							$content .= "@@2备注：" . $order['message'] . "\r";
						}

						$content .= "时间：" . date('Y-m-d H:i:s', $order['createtime']) . "\r";
						$content .= "\r\r\r\r<MK2></MK2>\r"; //控制切纸
					}
				}
			}

		} elseif ($machineType == 1) {
			//飞蛾
			if ($templateType == 0) {
				//普通打印
				if ($orderType == 'test') {
					$arr = array('酸菜鱼', '可乐鸡翅');
					$content = '';
					$content .= "<CB>** " . $title . " **</CB><BR><BR>";
					$content .= '<CB>桌号：01</CB><BR>';
					$content .= "订单编号：" . date('Y-m-d H:i:s') . "<BR>";
					$content .= "配送方式：" . $order['freight_text'] . "<BR>";
					$content .= "配送时间：<B>" . $order['freight_time'] . "</B><BR>";
					$content .= "收货人:<B>" . $order['linkman'] . "</B><BR>";
					$content .= "联系电话:<B>" . $order['tel'] . "</B><BR>";
					$content .= "收货地址:<B>" . $order['area'] . " " . $order['address'] . "</B><BR>";

					$content .= "下单时间：" . date('Y-m-d H:i:s') . "<BR>";
					$content .= "付款时间：" . date('Y-m-d H:i:s') . "<BR>";
					$content .= "付款方式：" . $order['paytype'] . "<BR><BR>";
					$content .= "商品名称     数量     总价<BR>";

					foreach ($arr as $key => $item) {
						$content .= "<BOLD>" . $item . "</BOLD>   1  33.6<BR>";
					}
					$content .= "<BR>";
					$content .= "备注：不要辣<BR>";
					$content .= "<RIGHT>实付金额：￥108.00</RIGHT>";
					$content .= "<BR><BR><BR><BR><BR><CUT>";
				} else {
					$content = '';
					$content .= "<CB>** " . $title . " **</CB><BR><BR>";
					if ($order['tableName']) {
						$content .= '<CB>桌号：' . $order['tableName'] . '</CB><BR>';
					}

					$content .= "订单编号：" . $order['ordernum'] . "<BR>";
					if ($orderType == 'restaurant_takeaway') {
						$content .= "配送方式：" . $order['freight_text'] . "<BR>";
						if ($order['freight_time']) {
							$content .= "配送时间：<B>" . $order['freight_time'] . "</B><BR>";
						}
						$content .= "收货人:<B>" . $order['linkman'] . "</B><BR>";
						$content .= "联系电话:<B>" . $order['tel'] . "</B><BR>";
						$content .= "收货地址:<B>" . $order['area'] . " " . $order['address'] . "</B><BR>";
					}

					$content .= "下单时间：" . date('Y-m-d H:i:s', $order['createtime']) . "<BR>";
					$content .= "付款时间：" . $paytime . "<BR>";
					$content .= "付款方式：" . $order['paytype'] . "<BR><BR>";
					$content .= "商品名称     数量     总价<BR>";

					foreach ($orderGoods as $item) {
						$content .= "<BOLD>" . $item['name'] . "(" . $item['ggname'] . ")</BOLD>   " . $item['num'] . "  " . $item['totalprice'] . "<BR>";
					}
					$content .= "<BR>";
					if ($order['message']) {
						$content .= "备注：<B>" . $order['message'] . "</B><BR><BR>";
					} else {
						$content .= "备注：无<BR>";
					}
					if ($order['tea_fee']) {
						$content .= "<RIGHT>" . $shop_set['tea_fee_text'] . "：￥" . $order['tea_fee'] . "</RIGHT><BR>";
					}
					if ($order['scoredk_money'] > 0) {
						$content .= "<RIGHT>积分抵扣：-￥" . $order['scoredk_money'] . "</RIGHT><BR>";
					}
					if ($order['leveldk_money'] > 0) {
						$content .= "<RIGHT>会员等级优惠：-￥" . $order['leveldk_money'] . "</RIGHT><BR>";
					}
					if ($order['coupon_money'] > 0) {
						$content .= "<RIGHT>优惠券：-￥" . $order['coupon_money'] . "</RIGHT><BR>";
					}
					if ($order['discount_money'] > 0) {
						$content .= "<RIGHT>优惠：-￥" . $order['discount_money'] . "</RIGHT><BR>";
					}
					$content .= "<RIGHT>实付金额：￥" . $order['totalprice'] . "</RIGHT>";
					$content .= "<BR><BR><BR><BR><BR><CUT>";
				}
			} elseif ($templateType == 1) {
				//一菜一单
				if ($orderType == 'test') {
					$time = date('Y-m-d H:i:s', time());
					$arr = array('酸菜鱼', '可乐鸡翅');
					$content = '';
					$num = count($arr);
					foreach ($arr as $key => $value) {
						$content .= '<CB>** 桌号：01 **</CB><BR>';
						$content .= '<C><L>' . $value . '  * 1</L></C><BR>';
						$content .= '<L>备注：不要辣，少盐</L><BR>';
						$content .= '时间：' . $time . '<BR>';
						$end = array_keys($arr);
//                        if(end($end)==$key){
						//                            break;
						//                        }else{
						$content .= '<BR><BR><BR><CUT>'; //控制切纸
						//                        }
					}
				} else {
					$content = '';
					foreach ($orderGoods as $key => $item) {
						if ($item['area_id'] != $area['id']) {
							continue;
						}

						$content .= '<CB>** 桌号：' . $order['tableName'] . ' **</CB><BR>';
						$content .= '<C><L>' . $item['name'] . "(" . $item['ggname'] . ")" . '  * ' . $item['num'] . '</L></C><BR>';
						if ($order['message']) {
							$content .= '<L>备注：' . $order['message'] . '</L><BR>';
						}

						$content .= '时间：' . date('Y-m-d H:i:s', $order['createtime']) . '<BR>';
						$content .= '<BR><BR><BR><CUT>'; //控制切纸
					}
				}

			}

		}
		return $content;
	}

	/**
	 * @param $orderType
	 * @param $orderInfo
	 * @param array $orderGoods
	 * @param  $templateType 打印类型（后台打印只打印一菜一单类型）  0普通打印，1一菜一单
	 * @return array
	 * 门店出单
	 */
	public static function print($orderType, $orderInfo, $orderGoods = [], $templateType = '') {
		if (is_int($orderInfo)) {
			$orderInfo = Db::name($orderType . '_order')->where('id', $orderInfo)->find();
			$orderGoods = Db::name($orderType . '_order_goods')->where('orderid', $orderInfo)->select()->toArray();
		}
		if (empty($orderGoods)) {
			$orderGoods = Db::name($orderType . '_order_goods')->alias('og')->where('orderid', $orderInfo['id'])->leftJoin('restaurant_product p', 'p.id=og.proid')
				->fieldRaw('og.*,p.area_id')->select()->toArray();
		}
//        Log::info([
		//            'file' => __FILE__,
		//            'line' => __LINE__,
		//            'orderInfo' => $orderInfo,
		//            'orderGoods' => $orderGoods
		//        ]);

		if ($orderInfo['tableid']) {
			$table = Db::name('restaurant_table')->where('aid', $orderInfo['aid'])->where('bid', $orderInfo['bid'])->where('id', $orderInfo['tableid'])->find();
			$orderInfo['tableName'] = $table['name'];
			$tablePrintIds = explode(',', $table['print_ids']);
		}

		$whereArea[] = ['aid', '=', $orderInfo['aid']];
		$whereArea[] = ['bid', '=', $orderInfo['bid']];
		if ($templateType !== '') {
			$whereArea[] = ['print_template_type', '=', $templateType];
		}

		$areaList = Db::name('restaurant_area')->where($whereArea)->select()->toArray();
//        Log::info([
		//            'file' => __FILE__,
		//            'line' => __LINE__,
		//            'areaList' => $areaList
		//        ]);
		if ($areaList) {
			foreach ($areaList as $area) {
				//不同菜品，选择不同区域
				if (empty($area['print_ids'])) {
					continue;
				}
				$machineList = Db::name('wifiprint_set')->where('aid', $orderInfo['aid'])->where('bid', $orderInfo['bid'])->whereIn('id', $area['print_ids'])->select()->toArray();
				if (empty($machineList)) {
					continue;
				}
//                Log::info([
				//                    'file' => __FILE__,
				//                    'line' => __LINE__,
				//                    'machineList' => $machineList
				//                ]);
				foreach ($machineList as $machine) {
					if ($orderInfo['freight_type'] == 1 || $orderInfo['freight_type'] == 5) {
						//自提订单,门店配送
						if ($machine['print_zt_type'] == 0) {
							continue;
						}

						if ($machine['print_zt_type'] == 2) {
							//指定门店
							$mdids = explode(',', $machine['print_zt_mdid']);
							if (!in_array($orderInfo['mdid'], $mdids)) {
								continue;
							}

						}
					}
					$content = \app\custom\Restaurant::restaurantPrintContent($machine['title'], $machine['type'], $area, $orderType, $orderInfo, $orderGoods);
					Log::info([
						'file' => __FILE__,
						'line' => __LINE__,
						'content' => $content,
					]);
					if (empty($content)) {
						continue;
					}

					if ($machine['type'] == 0) {
						$rs = \app\common\Wifiprint::yilianyun_print($machine['client_id'], $machine['client_secret'], $machine['access_token'], $machine['machine_code'], $machine['msign'], $content);
//                        return $rs;
					} elseif ($machine['type'] == 1) {
						$rs = \app\common\Wifiprint::feie_print($machine['client_id'], $machine['client_secret'], $machine['machine_code'], $machine['msign'], $content, $machine['machine_type']);
//                        return $rs;
					}
				}
			}
		}

		if ($tablePrintIds) {
			$machineList = Db::name('wifiprint_set')->where('aid', $orderInfo['aid'])->where('bid', $orderInfo['bid'])->whereIn('id', $tablePrintIds)->select()->toArray();
			if ($machineList) {
				foreach ($machineList as $machine) {
					$content = \app\custom\Restaurant::restaurantPrintContent($machine['title'], $machine['type'], ['print_template_type' => 0], $orderType, $orderInfo, $orderGoods);
					Log::info([
						'file' => __FILE__,
						'line' => __LINE__,
						'content' => $content,
					]);
					if (empty($content)) {
						continue;
					}

					if ($machine['type'] == 0) {
						$rs = \app\common\Wifiprint::yilianyun_print($machine['client_id'], $machine['client_secret'], $machine['access_token'], $machine['machine_code'], $machine['msign'], $content);
					} elseif ($machine['type'] == 1) {
						$rs = \app\common\Wifiprint::feie_print($machine['client_id'], $machine['client_secret'], $machine['machine_code'], $machine['msign'], $content, $machine['machine_type']);
					}
				}
			}
		}

		return ['status' => 1, 'msg' => '打印成功'];
	}

	public static function calculateCommission($aid, $product, $member, $commission_totalprice, $num) {
		if ($member['pid']) {
			$parent1 = self::getParentWithLevel($aid, $member['pid']);
			if ($parent1 && $parent1['levelData']['can_agent'] != 0) {
				$ogdata['parent1'] = $parent1['id'];
			}
		}
		if ($parent1['pid']) {
			$parent2 = self::getParentWithLevel($aid, $parent1['pid']);
			if ($parent2 && $parent2['levelData']['can_agent'] != 0) {
				$ogdata['parent2'] = $parent2['id'];
			}
		}
		if ($parent2['pid']) {
			$parent3 = self::getParentWithLevel($aid, $parent2['pid']);
			if ($parent3 && $parent3['levelData']['can_agent'] != 0) {
				$ogdata['parent3'] = $parent3['id'];
			}
		}
		if ($product['commissionset'] == 1) {
//按商品设置的分销比例
			$commissiondata = json_decode($product['commissiondata1'], true);
			if ($commissiondata) {
				if ($ogdata['parent1']) {
					$ogdata['parent1commission'] = $commissiondata[$parent1['levelData']['id']]['commission1'] * $commission_totalprice * 0.01;
				}

				if ($ogdata['parent2']) {
					$ogdata['parent2commission'] = $commissiondata[$parent2['levelData']['id']]['commission2'] * $commission_totalprice * 0.01;
				}

				if ($ogdata['parent3']) {
					$ogdata['parent3commission'] = $commissiondata[$parent3['levelData']['id']]['commission3'] * $commission_totalprice * 0.01;
				}

			}
		} elseif ($product['commissionset'] == 2) {
//按固定金额
			$commissiondata = json_decode($product['commissiondata2'], true);
			if ($commissiondata) {
				if ($ogdata['parent1']) {
					$ogdata['parent1commission'] = $commissiondata[$parent1['levelData']['id']]['commission1'] * $num;
				}

				if ($ogdata['parent2']) {
					$ogdata['parent2commission'] = $commissiondata[$parent2['levelData']['id']]['commission2'] * $num;
				}

				if ($ogdata['parent3']) {
					$ogdata['parent3commission'] = $commissiondata[$parent3['levelData']['id']]['commission3'] * $num;
				}

			}
		} elseif ($product['commissionset'] == 3) {
//提成是积分
			$commissiondata = json_decode($product['commissiondata3'], true);
			if ($commissiondata) {
				if ($ogdata['parent1']) {
					$ogdata['parent1score'] = $commissiondata[$parent1['levelData']['id']]['commission1'] * $num;
				}

				if ($ogdata['parent2']) {
					$ogdata['parent2score'] = $commissiondata[$parent2['levelData']['id']]['commission2'] * $num;
				}

				if ($ogdata['parent3']) {
					$ogdata['parent3score'] = $commissiondata[$parent3['levelData']['id']]['commission3'] * $num;
				}

			}
		} else {
			//按会员等级设置的分销比例
			if ($ogdata['parent1']) {
				if ($parent1['levelData']['commissiontype'] == 1) {
					//固定金额按单
					if ($istc1 == 0) {
						$ogdata['parent1commission'] = $parent1['levelData']['commission1'];
						$istc1 = 1;
					}
				} else {
					$ogdata['parent1commission'] = $parent1['levelData']['commission1'] * $commission_totalprice * 0.01;
				}
			}
			if ($ogdata['parent2']) {
				if ($parent2['levelData']['commissiontype'] == 1) {
					if ($istc2 == 0) {
						$ogdata['parent2commission'] = $parent2['levelData']['commission2'];
						$istc2 = 1;
					}
				} else {
					$ogdata['parent2commission'] = $parent2['levelData']['commission2'] * $commission_totalprice * 0.01;
				}
			}
			if ($ogdata['parent3']) {
				if ($parent3['levelData']['commissiontype'] == 1) {
					if ($istc3 == 0) {
						$ogdata['parent3commission'] = $parent3['levelData']['commission3'];
						$istc3 = 1;
					}
				} else {
					$ogdata['parent3commission'] = $parent3['levelData']['commission3'] * $commission_totalprice * 0.01;
				}
			}
		}
	}

	public static function getParentWithLevel($aid, $mid, $filter = []) {
		if (empty($mid)) {
			return [];
		}
		$parent = Db::name('member')->where('aid', $aid)->where('id', $mid)->find();
		if ($parent) {
			$parent['levelData'] = Db::name('member_level')->where('aid', $aid)->where('id', $parent['levelid'])->find();
		}
		return $parent;
	}
}